package com.webull.information.center.carwler.common.util.eljob;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.webull.information.center.carwler.common.model.ArchiveRel;
import com.webull.information.center.carwler.common.model.SpeclNewsPlan;

/**
 * @author shimingjun
 * @date 2016年8月30日 上午11:13:08
 * @version 1.0
 * @since JDK 1.8
 */
public class ElasticJobUtil {

	public static String getStr(List<Integer> shareItem) {
		if (shareItem == null || shareItem.isEmpty())
			return "";
		Collections.sort(shareItem);
		return ArrayUtils.toString(shareItem);
	}

	/**
	 * 根据分片总数和当前节点分片item,划分要处理的分类(例如:交易所Code)
	 * 
	 * @param context
	 * @param exchanges
	 * @return
	 * @since 0.1.0
	 */
	public static <T> List<T> shardingItems(ShardingContext context, List<T> exchanges) {
		if (context == null || exchanges == null)
			return exchanges;
		int sharding = context.getShardingItem();
		int totalCount = context.getShardingTotalCount();
		List<T> result = new ArrayList<>();
		for (int i = 0; exchanges != null && i < exchanges.size(); i++) {
			Integer mode = /* (exchanges.get(i).getId()) */i % totalCount;
			if (sharding == mode) {
				result.add(exchanges.get(i));
			}
		}
		return result;
	}

	public static void main(String[] args) {
		// JobExecutionMultipleShardingContext context = new
		// JobExecutionMultipleShardingContext();
		// context.setShardingTotalCount(2);
		// context.setShardingItems(Arrays.asList(1));
		// List<Integer> shardingItems = shardingItems(context, Arrays.asList(1, 2, 6));
		// System.out.println(ArrayUtils.toString(shardingItems));
	}

	public static List<SpeclNewsPlan> shardingPlan(ShardingContext context, List<SpeclNewsPlan> plans) {
		if (context == null || plans == null)
			return plans;
		int sharding = context.getShardingItem();
		int totalCount = context.getShardingTotalCount();
		List<SpeclNewsPlan> result = new ArrayList<>();
		for (int i = 0; plans != null && i < plans.size(); i++) {
			Integer mode = (plans.get(i).getId()) % totalCount;
			if (sharding == mode) {
				result.add(plans.get(i));
			}
		}
		return result;
	}

	/**
	 * 根据tickerId分片
	 * 
	 * @param context
	 * @param archiveRelList
	 * @return
	 */
	public static List<ArchiveRel> shardArchiveRel(ShardingContext context,
			List<ArchiveRel> archiveRelList) {
		if (context == null || archiveRelList == null)
			return archiveRelList;

		int sharding = context.getShardingItem();
		int totalCount = context.getShardingTotalCount();

		List<ArchiveRel> result = new ArrayList<>();
		for (ArchiveRel archiveRel : archiveRelList) {
			int mode = archiveRel.getWlId() % totalCount;
			if (sharding == mode) {
				result.add(archiveRel);
			}
		}
		return result;
	}
}
